package com.cy.src.client2;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.cy.src.aidl.IMyService;

public class MainActivity extends AppCompatActivity implements ServiceConnection {

    private IMyService iMyService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setupAidlService();
    }

    private void setupAidlService() {
//        方式一
        Intent intent = new Intent().setComponent(new ComponentName("com.cy.src.myaidl", "com.cy.src.myaidl.service.MyService"));
//        方式二 都可以
//        Intent intent = new Intent("com.cy.src.myaidl.service.MyService");
//        intent.setPackage("com.cy.src.myaidl");
        intent.addCategory(Intent.CATEGORY_DEFAULT);

        intent.putExtra("key","hello APP");
        startService(intent);
        bindService(intent, this, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(this);
    }

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

        Log.e("AIDL", "---onServiceConnected--------");
//        获取服务对象
        iMyService = IMyService.Stub.asInterface(iBinder);
        try {
            String s = iMyService.helloWorldAidl("APP 你好！");
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        Log.e("AIDL", "--onServiceDisconnected---------");
    }
}
